import {reactive, onMounted} from "vue";
import {apiParam} from "@/utils/index.js";
import {dictionAryApi} from "@/apis/CMS/frmDictionary/index.js";
import {skyMsgError} from "@/utils/sky.js";

// 1. 通过指定的字典类别编码间接获取字典信息
export function useSkyDict(dictType) {
  let dictCode = [];
  let skyDict = reactive({});
  onMounted(async () => {
    try {
      if (dictType.length > 0) {
        // 1. 获取字典类别
        const dictData = apiParam("2.0", "CMS.DicTypeDAL.GetSimpleList", []);
        const dictRes = await dictionAryApi(dictData);
        // 2. 获取字典编号
        for (const type of dictType) {
          dictRes.data.forEach(item => {
            if (item.DicTypeName === type) {
              dictCode.push(item.DicTypeCode);
            }
          });
        }
        // 3. 获取字典信息
        if (dictCode.length > 0) {
          for (const code of dictCode) {
            const data = apiParam("2.0", "CMS.DictionaryDAL.Querybypage",
              [
                {DicTypeCode: code},
                {
                  "pageIndex": 1,
                  "sortBy": "FDicTypeCode",
                  "direction": "asc",
                  "pageSize": 100000
                }
              ]);
            const res = await dictionAryApi(data);
            skyDict[code] = res.data.data;
          }
        }
      }
    } catch (error) {
      skyMsgError("字典查询失败，请刷新重试🌻");
    }
  });
  return {skyDict};
}

// 2. 直接通过字典类别获取字典信息 =>> 数据量如果过大会丢失数据(超过100w条)
export function newUseSkyDict(dictType) {
  let newSkyDict = reactive({});
  onMounted(async () => {
    try {
      if (dictType.length > 0) {
        const data = apiParam("2.0", "CMS.DictionaryDAL.Querybypage",
          [
            {DicTypeCode: ""},
            {
              pageIndex: 1,
              sortBy: "FDicTypeCode",
              direction: "asc",
              pageSize: 1000000
            }
          ]);
        const res = await dictionAryApi(data);
        // 2. 获取字典信息
        for (const type of dictType) {
          newSkyDict[type] = res.data.data.filter(item => item.DicTypeName === type);
        }
      }
    } catch (error) {
      skyMsgError("字典查询失败，请刷新重试🌻");
    }
  });
  return {newSkyDict};
}
